package com.example.demo.exception;



import com.example.demo.common.AppResult;
import com.example.demo.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


//处理全局异常的类
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    //返回AppResult
    @ResponseBody
    @ExceptionHandler(ApplicationException.class)
    public AppResult applicationExceptionHandler(ApplicationException e){
        //打印异常信息
        e.printStackTrace();

        //打印日志
        log.error(e.getMessage());
        if(e.getErrorResult()!= null){
            return e.getErrorResult();
        }

        //非空校验
        if(e.getMessage() == null || e.getMessage().equals("")){
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }

        //返回具体的异常信息
        return AppResult.failed(e.getMessage());

    }

    //兜底的异常

    public AppResult exceptionHandler(Exception e){
        //异常信息
        e.printStackTrace();

        //打印日志
        log.info(e.getMessage());

        if(e.getMessage() == null || e.getMessage().equals("")){
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }

        return AppResult.failed(e.getMessage());
    }



}
